package com.sgzn.sgpay.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.sgzn.sgpay.enums.ReturnResultState;
import com.sgzn.sgpay.enums.SgsResponseCode;
import com.sgzn.sgpay.exception.SgpayException;
import com.sgzn.sgpay.model.request.*;
import com.sgzn.sgpay.model.response.CurrentPageInfo;
import com.sgzn.sgpay.model.response.SgsResultResponse;
import com.sgzn.sgpay.model.response.result.ExchangeCoinInfoQueryPageResult;
import com.sgzn.sgpay.persistence.dao.TExchangeCoinInfoMapper;
import com.sgzn.sgpay.persistence.domain.TExchangeCoinInfo;
import com.sgzn.sgpay.persistence.domain.TExchangeCoinInfoExample;
import com.sgzn.sgpay.service.SgsExchangeCoinInfoService;
import com.sgzn.sgpay.service.support.SgsResponseUtil;
import com.sgzn.sgpay.util.PageCalculator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 兑换比例管理服务接口实现类
 * @author huangsenguang
 * @version Id: SgsExchangeCoinInfoServiceImpl.java, v 0.1 2018/4/25 21:10 huangsenguang Exp $$
 */
@Service
@Slf4j
public class SgsExchangeCoinInfoServiceImpl implements SgsExchangeCoinInfoService {
    @Autowired
    private TExchangeCoinInfoMapper tExchangeCoinInfoMapper;

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SgsResultResponse<String> addExchangeCoinInfo(SgsExchangeCoinInfoAddRequest request) {
        SgsResultResponse sgsResponse = new SgsResultResponse();
        TExchangeCoinInfo tExchangeCoinInfo = new TExchangeCoinInfo();
        tExchangeCoinInfo.setDeviceId(request.getDeviceId());
        tExchangeCoinInfo.setExchangeValue(request.getExchangeValue());
        tExchangeCoinInfo.setCreatedBy(request.getMchId());
        tExchangeCoinInfo.setCreatedAt(new Date());
        tExchangeCoinInfo.setUpdatedAt(new Date());
        int num = 0 ;
        try{
            num =  tExchangeCoinInfoMapper.insertSelective(tExchangeCoinInfo);
        }catch (DataAccessException e) {
            log.error("插入响应流水日志异常.{}", e);
        }
        if (num >= 1) {
            return SgsResponseUtil.INSTANCE.success(ReturnResultState.SUCCESS.getCode());
        } else {
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc(), ReturnResultState.FAIL.getCode());
        }
    }

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SgsResultResponse<String> deleteExchangeCoinInfo(SgsExchangeCoinInfoDeleteRequest request) {
        TExchangeCoinInfoExample example = new TExchangeCoinInfoExample();
        TExchangeCoinInfoExample.Criteria criteria = example.createCriteria();
        criteria.andDeviceIdEqualTo(request.getDeviceId());
        int num = 0 ;
        try{
            num =  tExchangeCoinInfoMapper.deleteByExample(example);
        }catch (DataAccessException e) {
            log.error("插入响应流水日志异常.{}", e);
        }

        if (num >= 1) {
            return SgsResponseUtil.INSTANCE.success(ReturnResultState.SUCCESS.getCode());
        } else {
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc(), ReturnResultState.FAIL.getCode());
        }
    }

    @Override
    public SgsResultResponse<TExchangeCoinInfo> queryExchangeCoinInfo(SgsExchangeCoinInfoQueryRequest request) {
        TExchangeCoinInfo tExchangeCoinInfo = null;
        TExchangeCoinInfoExample tExchangeCoinInfoExample = new TExchangeCoinInfoExample();
        tExchangeCoinInfoExample.createCriteria().andDeviceIdEqualTo(request.getDeviceId());
        List<TExchangeCoinInfo> tExchangeCoinInfos = tExchangeCoinInfoMapper.selectByExample(tExchangeCoinInfoExample);
        if (CollectionUtils.isEmpty(tExchangeCoinInfos)) {
            throw new SgpayException(SgsResponseCode.C_EXCHANGECOININFO_NOT_FOUND.getResponseCode(),SgsResponseCode.C_EXCHANGECOININFO_NOT_FOUND.getResponseDesc());
        }
        tExchangeCoinInfo = tExchangeCoinInfos.get(0);
        return SgsResponseUtil.INSTANCE.success(tExchangeCoinInfo);
    }

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SgsResultResponse<String> updateExchangeCoinInfo(SgsExchangeCoinInfoUpdateRequest request) {
        TExchangeCoinInfo record = new TExchangeCoinInfo();
        record.setDeviceId(request.getDeviceId());
        record.setExchangeValue(request.getExchangeValue());
        record.setUpdatedBy(request.getMchId());
        record.setUpdatedAt(new Date());

        TExchangeCoinInfoExample example = new TExchangeCoinInfoExample();
        TExchangeCoinInfoExample.Criteria criteria = example.createCriteria();
        criteria.andDeviceIdEqualTo(request.getDeviceId());
        int num = 0 ;
        try{
            num =  tExchangeCoinInfoMapper.updateByExampleSelective(record, example);
        }catch (DataAccessException e) {
            log.error("插入响应流水日志异常.{}", e);
        }

        if (num >= 1) {
            return SgsResponseUtil.INSTANCE.success(ReturnResultState.SUCCESS.getCode());
        } else {
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc(), ReturnResultState.FAIL.getCode());
        }
    }

    @Override
    public SgsResultResponse<ExchangeCoinInfoQueryPageResult> queryPage(SgsExchangeCoinInfoQueryPageRequest request) {
        try{
            ExchangeCoinInfoQueryPageResult result = new ExchangeCoinInfoQueryPageResult();
            TExchangeCoinInfoExample example = this.getTExchangeCoinInfoExampleByPage(request);
            int totalCount = this.tExchangeCoinInfoMapper.countByExample(example);//获取总数
            CurrentPageInfo pageInfo = PageCalculator.getPageInfo(totalCount, request.getPageQueryParam().getPageSize(),
                    request.getPageQueryParam().getCurrentPage());
            StringBuffer clause = new StringBuffer();
            //加上起始和结束行号进行列表查询
            clause.append("created_at desc ");
            clause.append("limit ").append(pageInfo.getStartIndex()).
                    append(",").append(pageInfo.getPageSize());
            example.setOrderByClause(clause.toString());
            List<TExchangeCoinInfo> list = tExchangeCoinInfoMapper.selectByExample(example);

            result.setExchangeCoinInfoList(list);
            result.setCurrentPage(pageInfo.getCurrentPage());
            result.setPageSize(pageInfo.getPageSize());
            result.setTotalCount(totalCount);
            result.setTotalPage(pageInfo.getTotalPage());
            return SgsResponseUtil.INSTANCE.success(result);
        }catch (Exception e){
            log.error("兑换比例分页查询系统异常：",e);
            return SgsResponseUtil.INSTANCE.fail(SgsResponseCode.C503.getResponseCode(),SgsResponseCode.C503.getResponseDesc());
        }
    }

    /**
     * 获取查询对象
     * @param request
     * @return
     */
    private TExchangeCoinInfoExample getTExchangeCoinInfoExampleByPage(SgsExchangeCoinInfoQueryPageRequest request){
        TExchangeCoinInfoExample countExample = new TExchangeCoinInfoExample();
        TExchangeCoinInfoExample.Criteria cra = countExample.createCriteria();
        if(StringUtils.isNotBlank(request.getDeviceId())){
            cra.andDeviceIdEqualTo(request.getDeviceId());
        }
        if(StringUtils.isNotBlank(request.getExchangeValue())){
            cra.andExchangeValueEqualTo(request.getExchangeValue());
        }
        return countExample;
    }
}

